package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.common.vo.Result;
import com.changgou.pay.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/weixin/pay")
public class WeixinPayController {

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.pay.exchange.order}")
    private String orderExchange;

    @Value("${mq.pay.routing.key}")
    private String orderRoutingKey;



    /**
     * 创建支付二维码链接
     * @param requestParamMap 请求参数；包含内容如下：
        *                        outTradeNo 订单号
        *                        money 支付金额
     * @return
     */
    @GetMapping("/create/native")
    public Result<Map<String,String>> createNative(@RequestParam Map<String,String> requestParamMap){
        Map<String,String> map = weixinPayService.createNative(requestParamMap);
        return new Result<>("创建支付二维码链接地址成功！",map);
    }

    /**
     * 根据订单号查询订单
     * @param outTradeNo:订单号
     * @return
     */
    @GetMapping("/query/status")
    public Result<Map<String,String>> querystatus(String outTradeNo){
        Map<String,String> map=weixinPayService.querystatus(outTradeNo);
        return new Result<>("",map);
    }

    /**
     * 接收支付成功的通知
     * @param request 请求对象
     * @return 返回结果
     */
    @RequestMapping("/callback")
    public String callback(HttpServletRequest request){

        try {
            //获取输入流
            ServletInputStream requestInputStream = request.getInputStream();

            //定义输出对象
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len=0;
            while ((len=requestInputStream.read(buffer))!=-1){
                byteArrayOutputStream.write(buffer,0,len);
            }

            //获取到对应的xml
            //将输出内容转换到一个字符串
            String xmlStr=new String(byteArrayOutputStream.toByteArray(),"utf-8");
            System.out.println("微信支付成功之后返回的信息：" + xmlStr);

            //关闭资源
            byteArrayOutputStream.close();
            requestInputStream.close();


            //返回给微信的数据:字符串转为json
            Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
            String jsonStr = JSON.toJSONString(map);
            System.out.println("返回的内容转换为json：" + jsonStr);

            //发送支付信息到MQ
            rabbitTemplate.convertAndSend(orderExchange,orderRoutingKey,jsonStr);

            //返回给微信的数据
            Map<String, String> returnMap = new HashMap<>();
            returnMap.put("return_code", "SUCCESS");
            returnMap.put("return_msg", "OK");

            String xml = WXPayUtil.mapToXml(returnMap);
            System.out.println("返回给微信支付系统的结果：" + xml);
            return xml;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
